package lotterysystem.lotterysystem.service.Impl;

import jakarta.annotation.Resource;
import lotterysystem.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import lotterysystem.lotterysystem.common.exception.ServiceException;
import lotterysystem.lotterysystem.common.utils.RedisUtil;
import lotterysystem.lotterysystem.common.utils.RegexUtil;
import lotterysystem.lotterysystem.service.VerificationCodeService;
import lotterysystem.lotterysystem.common.utils.CaptchaUtil;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;

    @Resource
    private RedisUtil redisUtil;
    @Override
    public String sendVerificationCode(String phoneNumber) {
        // 校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }


        // 生成随机验证码
        String code = CaptchaUtil.getCaptcha(4);

        // 缓存验证码
        String codeKey = VERIFICATION_CODE_PREFIX + phoneNumber;
        redisUtil.set(codeKey, code, VERIFICATION_CODE_TIMEOUT);

        // 发送验证码（实际项目中这里应该调用短信服务）
        System.out.println("发送验证码到手机号: " + phoneNumber + ", 验证码: " + code);
        return code;

    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        // 校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
